<script setup>
import { GetListAPI } from '@/api/system/printConfig'
import { GetDeiltListAPI } from '@/api/warehouse/incomingPrint/pring'
import { printAPI } from '@/api/supplierLabel/outsourcPrint/outsourcPrint.js'

const emit = defineEmits()

const templateSel = ref([])
const route = useRoute()
const getSel = async () => {
  const res = await GetListAPI({
    pageNum: 1,
    pageSize: 9999,
    printRouting: route.path.indexOf('-data') != -1 ? route.path.substring(0, route.path.indexOf('-data')) : route.path
  })
  templateSel.value = res.rows.map(item => ({
    label: item.printName,
    value: item.printId
  }))
}
getSel()
const printViewRef = ref(null)
const ruleFormRef = ref(null)
const { proxy } = getCurrentInstance()

const props = defineProps({
  data: {
    type: Object,
    default: () => {}
  }
})
// 封装 方法 字典查询
const { sys_print_type } = proxy.useDict('sys_print_type')
const ruleForm = reactive({
  id: '',
  templateId: '',
  subcontractingOrderNum: '', // 采购订单
  materialCode: '', // 物料编码
  materialName: '', // 物料名称
  materialSpec: '', // 物料规格
  specType: '', // 规格型号
  quantityDemanded: '', // 采购数量
  quantityDemandedStr: '', // 采购数量字符串拼接单位
  quantityPrinted: '', // 已打印数量
  quantityPrintedStr: '', // 已打印数量字符串拼接单位
  productionDate: '', //
  productionLot: '', //
  tagNum: '', // 标签张数
  materialNumber: '', //
  materialUnit: '', // 单位
  lotQuantity: '', //本批数量
  lotQuantityStr: '', //本批数量字符串拼接单位
  list: []
})

const printForm = ref()
const printFormList = ref([])
const submit = () => {
  return new Promise((resolve, reject) => {
    ruleFormRef.value.validate((valid, fields) => {
      try {
        if (Number(ruleForm.avgNum) > Number(ruleForm.lotQuantity))
          return proxy.warningMsg('本批数量必须大于等于包装数量，请重新输入！')
        if (Number(ruleForm.lotQuantity) + Number(ruleForm.quantityPrinted) > Number(ruleForm.quantityDemanded))
          return proxy.warningMsg('本批数量+已打印数量不可超出采购数量,请重新输入！')
        if (valid) {
          resolve(ruleForm)
        } else {
          proxy.formMsg()
          resolve(false)
        }
      } catch (e) {
      } finally {
      }
    })
  })
}
// 打印标签
const printFn = async () => {
  try {
    const res = await printAPI({
      id: ruleForm.id,
      subcontractingOrderNum: ruleForm.subcontractingOrderNum,
      materialCode: ruleForm.materialCode,
      productionDate: ruleForm.productionDate,
      productionLot: ruleForm.productionLot,
      tagNum: ruleForm.tagNum,
      avgNum: ruleForm.avgNum,
      lotQuantity: ruleForm.lotQuantity,
      mantissa: ruleForm.mantissa
    })
    ruleForm.list = res.data
    const result = await printViewRef.value.print()
    if (!result) return
  } catch (error) {}
}

const receiveTypeChange = val => {
  printViewRef.value.getConfig(val)
}

// 计算标签数量和尾数
const labelCount = computed(() => {
  const quantity = ruleForm.lotQuantity
  const packaging = ruleForm.avgNum
  if (quantity && packaging) {
    return Math.floor(quantity / packaging) // 标签数量
  }
  return 0
})

const tailCount = computed(() => {
  const quantity = ruleForm.lotQuantity
  const packaging = ruleForm.avgNum
  if (quantity && packaging) {
    return quantity % packaging // 尾数
  }
  return 0
})

// 更新表单中的标签数量和尾数
watch([() => ruleForm.lotQuantity, () => ruleForm.avgNum], () => {
  ruleForm.tagNum = labelCount.value
  ruleForm.mantissa = tailCount.value
})

const getData = async () => {
  try {
    const res = await GetDeiltListAPI({
      pageNum: 1,
      pageSize: 9999,
      id: ruleForm.id
    })

    printFormList.value = res.rows
  } catch (error) {
    // console.log(error)
  } finally {
  }
}

// watch(
//   () => ruleForm.dateManufacture,
//   () => {
//     if (printFormList.value?.length)
//       printFormList.value.forEach(item => (item.dateManufacture = ruleForm.dateManufacture))
//   },
//   {
//     deep: true,
//     immediate: true
//   }
// )

/**
 * 监听回显
 */
watch(
  () => props.data,
  () => {
    for (let key in props.data) {
      ruleForm[key] = props.data[key]
    }
    // 本批数量字符串拼接
    ruleForm.lotQuantityStr = `${ruleForm.lotQuantity || ''}` + `${ruleForm.materialUnit}`
    // 采购数量字符串拼接
    ruleForm.quantityDemandedStr = `${ruleForm.quantityDemanded}` + `${ruleForm.materialUnit}`
    // 已打印数量字符串拼接
    ruleForm.quantityPrintedStr = `${ruleForm.quantityPrinted}` + `${ruleForm.materialUnit}`
  },
  {
    deep: true,
    immediate: true
  }
)
defineExpose({
  submit,
  printFn
})
</script>
<template>
  <div class="app-container">
    <el-form :model="ruleForm" ref="ruleFormRef" label-width="120px" status-icon inline>
      <el-form-item
        label="打印模板"
        prop="templateId"
        :rules="[
          {
            required: true,
            message: '请选择打印模板',
            trigger: 'change'
          }
        ]"
      >
        <el-select v-model="ruleForm.templateId" clearable placeholder="请选择打印模板" @change="receiveTypeChange">
          <el-option v-for="(item, index) in templateSel" :key="index" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item
        label="生产日期"
        prop="productionDate"
        :rules="[
          {
            required: true,
            message: '请选择生产日期',
            trigger: 'change'
          }
        ]"
      >
        <el-date-picker value-format="YYYY-MM-DD HH:mm:ss" v-model="ruleForm.productionDate" placeholder="请选择日期" />
      </el-form-item>
      <el-form-item label="委外订单">
        <el-input disabled v-model="ruleForm.subcontractingOrderNum" />
      </el-form-item>
      <!-- <el-form-item
        label="生产批次"
        prop="productionLot"
        :rules="[
          {
            required: true,
            message: '请输入生产批次',
            trigger: 'blue'
          }
        ]"
      >
        <el-input v-model="ruleForm.productionLot" />
      </el-form-item> -->
      <el-form-item label="物料编码">
        <el-input disabled v-model="ruleForm.materialCode" />
      </el-form-item>
      <el-form-item label="物料名称">
        <el-input disabled v-model="ruleForm.materialName" />
      </el-form-item>
      <el-form-item label="物料规格">
        <el-input disabled v-model="ruleForm.materialSpec" />
      </el-form-item>
      <el-form-item label="规格型号">
        <el-input disabled v-model="ruleForm.specType" />
      </el-form-item>
      <el-form-item label="采购数量">
        <el-input disabled v-model="ruleForm.quantityDemanded">
          <template #append>{{ ruleForm.materialUnit }}</template>
        </el-input>
      </el-form-item>
      <el-form-item
        label="本批数量"
        prop="lotQuantity"
        :rules="[
          {
            required: true,
            message: '请输入本批数量',
            trigger: 'blur'
          }
        ]"
      >
        <el-input type="number" @input="quantityInput" :min="1" v-model="ruleForm.lotQuantity">
          <template #append>{{ ruleForm.materialUnit }}</template>
        </el-input>
      </el-form-item>
      <el-form-item label="已打印数量">
        <el-input disabled v-model="ruleForm.quantityPrinted">
          <template #append>{{ ruleForm.materialUnit }}</template>
        </el-input>
      </el-form-item>
      <el-form-item
        prop="avgNum"
        label="包装数量"
        :rules="[
          {
            required: true,
            message: '请输入包装数量',
            trigger: 'blur'
          }
        ]"
      >
        <el-input v-model="ruleForm.avgNum" type="number" />
      </el-form-item>

      <el-form-item label="标签数量">
        <el-input disabled v-model="ruleForm.tagNum" />
      </el-form-item>

      <el-form-item label="尾数">
        <el-input disabled v-model="ruleForm.mantissa" />
      </el-form-item>
      <div class="rk">
        <el-form-item label="模板样式">
          <PrintView ref="printViewRef" :templateId="ruleForm.templateId" :printData="ruleForm.list" />
        </el-form-item>
      </div>
    </el-form>
  </div>
</template>

<style lang="scss" scoped>
.rk ::v-deep .el-form-item {
  width: 100% !important;
}
</style>
